package com.buaa.aimall.Utils.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.buaa.aimall.goodsModule.Entity.TransactionOrderEntity;
import com.buaa.aimall.goodsModule.Service.TransactionOrderService;
import com.buaa.aimall.Utils.Config.CleanupProperties;
import com.buaa.aimall.Utils.Enum.PaymentStatus;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

@Service
@Slf4j
public class CleanupService {
    
    @Autowired
    private TransactionOrderService transactionOrderService;
    
    @Autowired
    private CleanupProperties cleanupProperties;
    
    @Transactional
    public void cleanupExpiredOrders() {
        try {
            LocalDateTime beforeTime = LocalDateTime.now()
                .minusMinutes(cleanupProperties.getExpiredOrderMinutes());
            
            LambdaQueryWrapper<TransactionOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(TransactionOrderEntity::getCreateTime, beforeTime);
            queryWrapper.eq(TransactionOrderEntity::getPaymentStatus, PaymentStatus.PAYING);
            
            long count = transactionOrderService.count(queryWrapper);
            
            if (count > 0) {
                LambdaUpdateWrapper<TransactionOrderEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(TransactionOrderEntity::getPaymentStatus, PaymentStatus.PAYING)
                    .lt(TransactionOrderEntity::getCreateTime, beforeTime)
                    .set(TransactionOrderEntity::getPaymentStatus, PaymentStatus.CANCELLED);
                
                boolean success = transactionOrderService.update(null, updateWrapper);

                if (success) {
                    log.info("成功删除 {} 个超时订单", count);
                } else {
                    log.warn("删除超时订单失败");
                }
            }
            else{
                log.info("没有超时订单");
            }
        } catch (Exception e) {
            log.error("删除超时订单时发生错误", e);
            throw e;
        }
    }
}